package icu.wdtt.service.Impl;


import cn.dev33.satoken.secure.SaSecureUtil;
import com.github.pagehelper.PageHelper;
import icu.wdtt.Utils.EmailSendUtils;
import icu.wdtt.exception.UserException;
import icu.wdtt.mapper.FilesMapper;
import icu.wdtt.mapper.RoleMapper;
import icu.wdtt.mapper.UserMapper;
import icu.wdtt.model.RasKey;
import icu.wdtt.model.Role;
import icu.wdtt.model.User;
import icu.wdtt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmailSendUtils emailSendUtils;

    /**
     * 后台添加用户
     * @param username 用户名
     * @param password 密码
     * @param email 邮箱
     * @param roleName 角色名称
     * @return 结果
     */
    @Override
    public Boolean setUser(String username, String password, String email, String roleName) throws Exception  {
        Boolean userName = this.isUserName(username);
        if(!userName) {
            throw new UserException("该用户名已经存在!");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        System.out.println(user);
        List<Role> roleList = roleMapper.getName(roleName);
        user.setRoleList(roleList);
        this.add(user);
        return true;
    }

    @Override
    public User get(@NotNull@Min(0) int uid) {
        return userMapper.get(uid);
    }

    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }



    /**
     * 删除用户
     * @param uid 用户id
     * @return 返回结果
     */
    @Override
    public Boolean del(@NotNull@Min(0) int uid) {
            userMapper.delUserAndRole(uid);
            userMapper.delUserAndFiles(uid);
            userMapper.del(uid);
            return true;
    }

    /**
     * 更新用户信息
     * @param user 用户对象
     * @return 返回结果
     */
    @Override
    public Boolean update(@NotNull User user) {

            userMapper.update(user);
            userMapper.delUserAndRole(user.getUid());
            user.getRoleList().forEach(r->userMapper.addUserAndRole(user.getUid(),r.getRid()));
            return true;
    }

    /**
     * 添加用户
     * @param user 用户对象
     * @return 返回结果
     */
    @Override
    public Boolean add(@NotNull User user) {
            userMapper.add(user);
            if(user.getUid() > 0){
                for (Role role : user.getRoleList()) {
                    userMapper.addUserAndRole(user.getUid(),role.getRid());
                }
                return true;
            }
        return false;
    }

    /**
     * 登陆方法
     * @param username 用户名
     * @param password 密码
     * @return 用户对象
     */
    @Override
    public User login(@NotBlank String username, @NotBlank String password) throws UserException {

            User login = userMapper.login(username, password);
            if(login !=null) {
                login = userMapper.get(login.getUid());
                return login;
            }else{
                throw  new UserException("用户名或其密码错误");
            }
    }

    /**
     * 分页查询用户
     * @param pageNum 当前页面
     * @param pageSize 页面分几条
     * @return 用户集合
     */
    @Override
    public List<User> getPage(@Min(0) int pageNum, int pageSize) {

            if(pageSize < 1){
                pageSize=10;
            }
            PageHelper.startPage(pageNum,pageSize);
            List<User> userList = this.getAll();

            if(userList != null){
                return userList;
            }
        return null;
    }

    /**
     * 注册用户
     * @param username 用户名
     * @param password 用户密码
     * @param email 邮箱
     * @return 结果
     */
    @Override
    public Boolean register(String username , String password,String email) {

            User user = new User();
            Boolean userNameFlag = this.isUserName(username);
            if(!userNameFlag){
                return false;
            }
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            List<Role> roleNameList = roleMapper.getName("普通用户");
            user.setRoleList(roleNameList);
            Boolean flag = this.add(user);
            if(flag){
                return true;
            }
        return false;
    }

    /**
     * 判断用户名是否存在
     * @param username 用户名
     * @return true为不存在 false存在
     */
    @Override
    public Boolean isUserName(String username) {
        User userByUserName = userMapper.getUserByUserName(username);
        if(userByUserName != null){
            return false;
        }
        return true;
    }

    /**
     * 验证邮箱验证码是否正确
     * @param code 邮箱验证码
     * @param emailId tokenId值
     * @return 返回结果
     */
    public Boolean isEmail(String code , String emailId) {
        Boolean flag = emailSendUtils.isCode(code, emailId);
        return flag;
    }

    /**
     * 根据邮箱重置密码
     * @param username 用户名
     * @param email 邮箱
     * @param emailCode 邮箱验证码
     * @param password 重新设置的密码
     * @param emailId 邮箱token
     * @return 结果
     * @throws UserException 各种报错提示信息
     */
    public Boolean retPassword(String username ,String email ,String emailCode,String password,String emailId) throws UserException {
        //检验邮箱验证码
        Boolean emailFlag = emailSendUtils.isCode(emailCode,emailId);
        if(!emailFlag)throw new UserException("邮箱验证码错误!");
        //检验当前用户是否存在
        User user = userMapper.getUserByUserName(username);
        if(user == null) throw  new UserException("该用户名不存在!");
        //检验邮箱地址是否正确
        if(!user.getEmail().equals(email))throw new UserException("邮箱地址与当前用户不符！");
        //修改密码
        Boolean flag = this.updatePassword(user.getUid(),user.getPassword(), password);
        if(!flag)throw new UserException("当前系统维护中，请稍后在重置密码!");
        //成功 将验证码的token删除 消除占用的内存
        emailSendUtils.delCode(emailId);
        return true;
    }

    /**
     * 根据密码修改密码
     * @param uid 用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 结果
     */
    public Boolean updatePassword(int uid,String oldPassword ,String newPassword) {
            userMapper.updatePassword(uid,oldPassword,newPassword);
            return true;
    }

    /**
     * 返回所有用户，包括其角色
     * @return
     */
    @Override
    public List<User> getUserAndRoleAll() {
        return userMapper.getUserAndRoleAll();
    }

    /**
     * 返回指定uid用户 包含其角色
     * @param uid
     * @return
     */
    @Override
    public User getUserAndRoleByUid(int uid) {
        return userMapper.getUserAndRoleByUid(uid);
    }

    /**
     * 返回所有用户，并且携带他们的文件信息
     * @return
     */
    @Override
    public List<User> getUserAndFilesAll() {
        return userMapper.getUserAndFilesAll();
    }

    /**
     * 返回指定uid用户信息，并且携带他的文件信息
     * @param uid
     * @return
     */
    @Override
    public User getUserAndFilesByUid(int uid) {
        return userMapper.getUserAndFilesByUid(uid);
    }


}
